<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Query\GoodsQuery;
use Illuminate\Http\Request;
use App\Model\GoodsMaster;

class GoodsController extends Controller
{
    /**
     * 商品情報
     * 商品一覧
     */
    function index(Request $request)
    {
        try{
            $goodsQuery = new GoodsQuery();
            $goodsCode = $goodsQuery->getGoodsCode();
            return view('admin.goods', array(
                'goodsCode' => $goodsCode
            ));
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    function doQuery(Request $request)
    {
        $goodsQuery = new GoodsQuery();
        $goods = $goodsQuery->getGoods();
        return view('admin.goodslist', array(
            'goods' => $goods
        ));
    }

    /**
     * 商品情報
     * 新規 修正
     */
    function doSelect(Request $request)
    {
       try{
            $goods_id = $request->input('goods_id');
            $goods = null;
            $goodsQuery = new GoodsQuery();
            $goodsCode = $goodsQuery->getGoodsCode();
            $cateCode = $goodsQuery->getCateCode();
            $suppCode = $goodsQuery->getSuppCode();
            if (! empty($goods_id)) {

                $goods = $goodsQuery->getGoodsInfoByGoodsid($goods_id);
                $goodsModel = $goodsQuery->getGoodsModelByGoodsId($goods_id);
            } else {
                $goodsMst = new GoodsMaster();
                $goods = array(
                    0 => $goodsMst
                );

                $goodsModel =[];
            }

            $goodsinfos = [
                $goods[0],
                $goodsCode,
                $cateCode,
                $suppCode,
                $goodsModel
            ];

            return view('admin.goods', array(
                'goodsinfos' => $goodsinfos
            ));
         }catch (\Exception $e){
           \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }

    }

    /**
     * 商品情報
     * チェック商品コード 存在するかどうか
     */
    public function goodsCodeJson(Request $request)
    {
       try{
            $goodsCode =$_POST['goodCode'];

            $goodsQuery = new GoodsQuery();
            $flag = $goodsQuery->getCheckGoodsJson($goodsCode);

            if(!empty($flag)){
                $status=1;
            }else{
                $status=0;
            }
            echo json_encode($status);
         }catch (\Exception $e){
             \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
       }
    }


    /**
     * 商品情報 型番 カラー サイズ
     * 修正の時 削除
     */
    public function goodsDeleteJson(Request $request)
    {
       try{
            $modelId =$_POST['goodModelId'];
            $goodsQuery = new GoodsQuery();
            $flag = $goodsQuery->deleteUpdateGoodsJson($modelId);

            if(!empty($flag)){
                $status=1;
            }else{
                $status=0;
            }
            echo json_encode($status);
         }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * 商品情報
     * 商品情報を登録する
     */
    function doSave(Request $request)
    {
       try{
            $goodsQuery = new GoodsQuery();
            $goodsInfo = $request->input('goodsInfo');
            $goodsModel = $request->input('goodsModelInfo');
            $goodsid = $goodsInfo['goods_id'];
            $goodsCode = $goodsInfo['goods_code'];
            $lengthModel = count($goodsModel)/3;
            //$lengthModelUpdate = count($goodsModel)/3;

            if (empty($goodsid)) {

                $flag = $goodsQuery->getCheckGoodsJson($goodsCode);
                if(!empty($flag)){
                    echo ("<script type='text/javascript'> alert('商品コードが存在しました');history.go(-1);</script>");
                    exit;
                }

                $file = $request->file('photo');
                if (empty($file)) {
                    echo "<script type=\"text/javascript\">alert(\"アップロードの画像を選択してください!\");window.history.go(-1);</script>";
                    exit();
                }
                $allowed_extensions = [
                    "png",
                    "jpg",
                    "gif",
                    "jpeg",
                    "bmp",
                    "webp"
                ];
                if ($file->getClientOriginalExtension() && ! in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                    return [
                        'error' => 'You may only upload png, jpg，jpeg，bmp or gif.'
                    ];
                }
                // public フォルダのパス uploads/images
                $destinationPath = 'uploads/images/';
                $extension = $file->getClientOriginalExtension();
                // 随机生成的字符串,可以自行拼接图片名字
                $fileName = str_random(10) . '.' . $extension;
                $file->move($destinationPath, $fileName);
                $ext_name = substr(strstr($fileName, '.'), 1);

                $goodsQuery->addGoodsMaster($goodsInfo);
                $goodsUuid = $goodsQuery->selectGoodsIdByGoodsCode($goodsCode);

                $param = array(
                    array_column($goodsUuid, 'goods_id')[0],
                    '/uploads/images/',
                    $fileName,
                    $ext_name
                );
                $goodsModel['goods_id'] = array_column($goodsUuid, 'goods_id')[0];

                $flag = $goodsQuery->addGoodsPictureModel($param, $goodsModel, $lengthModel);
            } else {

                $goodsUpdateModel = $request->input('goodsUpdateModel');

                $fileName = "";
                $ext_name = "";

                $file = $request->file('photo');
                $fileParam = array();
                if (! empty($file)) {
                    $allowed_extensions = [
                        "png",
                        "jpg",
                        "gif",
                        "jpeg",
                        "bmp",
                        "webp"
                    ];
                    if ($file->getClientOriginalExtension() && ! in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                        return [
                            'error' => 'You may only upload png, jpg，jpeg，bmp or gif.'
                        ];
                    }
                    // public フォルダのパス uploads/images
                    $destinationPath = 'uploads/images/';
                    $extension = $file->getClientOriginalExtension();
                    // 随机生成的字符串,可以自行拼接图片名字
                    $fileName = str_random(10) . '.' . $extension;
                    $file->move($destinationPath, $fileName);
                    $ext_name = substr(strstr($fileName, '.'), 1);
                }
                $list = 'goods_id';
                $data = $goodsid;
                $goodsInfo['updated_at'] = now();
                if(!empty($file)){
                    $fileParam = array(
                        $fileName,
                        $ext_name,
                        $goodsid
                    );

                }
                $goodsQuery = new GoodsQuery();
                $flag = $goodsQuery->updateGoodsMaster($list, $data, $goodsInfo, $fileParam,$goodsModel,$lengthModel, $file,$goodsid,$goodsUpdateModel);

            }
            if ($flag) {
                return redirect('/admin/goods');
            }
         }catch (\Exception $e){
             echo $e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage();
           \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
       }

    }

    function getGoods()
    {
        $code = $_POST['goodCode'];
        $goodsQuery = new GoodsQuery();
        $goodsCode = $goodsQuery->getGoodsInfoByGoodsCode($code);
        return json_encode($goodsCode[0]);
    }

    // cancel
    function doCancel(Request $request)
    {
        $code = $request->input('goods_code', '');
        // $goodsController=new GoodsController();
        $goodsQuery = new GoodsQuery();
        $goodsCode = $goodsQuery->getGoodsCode();
        for ($x = 0; $x < count($goodsCode); $x ++) {
            if ($code == $goodsCode[$x]) {
                $goods = $goodsQuery->doQuery($code);
            }
        }
        return view('admin.goods', array(
            'goods' => $goods[0]
        ));
        if ($goods == "") {
            return view('admin.goods');
        }
    }

    /**
     * 商品情報
     * 商品情報を削除する
     */
    function doDelete(Request $request)
    {
        try{
                $code = $request->input('goods_id');
                $goodsQuery = new GoodsQuery();
                $flag = $goodsQuery->deleteGoodsByGoodsCode($code);

                if ($flag) {
                    $mesIfo = "削除成功！";
                } else {
                    $mesIfo = "削除失敗！";
                }

                session([
                    'mesIfo' => $mesIfo
                ]);
                return redirect('/admin/goods');
           }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }
}
?>
